<template>
    <div id="editorContainer" ref="editorContainer"
         @mousedown="mouse_down"
         @touchstart="mouse_down"
         @scroll="editorContainerScroll($event)"
         :typesad="editorType"
         :style="{backgroundColor: (editorData && editorData.backgroundColor) || 'transparent', overflowY: editorType === EditorType.PerformanceTeaching ? 'hidden' : 'scroll'}">
        <!--@mousemove="mouse_move" @mouseup="mouse_up"-->
        <!-- @touchmove="mouse_move"
         @touchend="mouse_up" -->
        <!--        <div class="courseWareContentBox" v-html="courseWareData"></div>-->
        <div class="transformBox"
             :style="{transformOrigin: transformOriginString, transform: `scale(${scale})`}"
             id="editor_svg_container">
            <music-score :editorType="editorType" v-if="isNeedMusicScore()" v-show="musicScoreDataNotnull"
                         ref="musicScore" :playHelper="playHelper"/>
            <music-score-sync-time v-if="isNeedMusicScoreSyncTimme()"
                                   ref="musicScoreSyncTime" :playHelper="playHelper"/>
            <sketchpad ref="sketchpad" :playHelper="playHelper" :editorType="editorType"
                       v-if="editorType !== EditorType.PerformanceTeaching"
                       @setScaleValue="setScaleValue" @setTransformOrigin="setTransformOrigin"
                       @sketchpadTypeChange="sketchpadTypeChangeFun"/>
        </div>
    </div>
</template>

<script>

    import MusicScoreSyncTime from "../../music-score/components/MusicScoreSyncTime";

    const {
        OpenJMCFile
    } = require('../../../js/open-jmc-file');
    const {FileHelper, Folder} = require('../../../../../public/file-helper/file-helper');
    const {
        Editor
    } = require('../js/editor');
    const {
        JMCData
    } = require('../js/jmc-data');
    const {
        EditorType,
        SketchpadType
    } = require('../js/config');
    const {
        CommandTargetType
    } = require('../js/command');
    const {
        EditorData,
        EditorAction
    } = require('../../sketchpad/js/index');
    const {
        EditorControlMixin
    } = require('../js/editor-control-mixin');
    const {FileType} = require('../../music-score/js/music-score-const');
    const {MidiParserData} = require('../../midi-parser/js/midi-parser-data');
    const LeftConfig = require('../../left-components/js/left-config');
    import MusicScore from "../../music-score/components/MusicScore";
    import Sketchpad from "../../sketchpad/components/Sketchpad";
    import {hex_sha1} from "../../../js/sha1";
    const {Download} = require('../../../js/download');

    export default {
        name: "Editor",
        components: {MusicScoreSyncTime, Sketchpad, MusicScore},
        props: ['playHelper', 'courseWareData'],
        mixins: [EditorControlMixin],
        data() {
            return {
                scale: 1,
                musicScoreDataNotnull: false,
                editorData: null,
                syncTime: false,
                transformOriginString: '0 0'
            }
        },
        created() {
            this.EditorType = EditorType;
            this.$bus.on(EventBusObsNames.DrawPageAction, this.pageAction);
            this.$bus.on(EventBusObsNames.DrawToolsAction, this.toolsAction);
            this.$bus.on(EventBusObsNames.DrawToolsChangeType, this.toolsChangeType);
            this.$bus.on(EventBusObsNames.DrawOpenFile, this.onOpenFile);
            this.$bus.on(EventBusObsNames.DrawInsertFile, this.onInsertFile);
            this.onCreated();
            this.editor = new Editor(this.editorShared);
        },
        mounted() {
            this.editorContainer = $('#editorContainer');
            this.$refs.sketchpad && (this.editor.sketchpad = this.$refs.sketchpad.sketchpad);
            this.$refs.musicScore && (this.editor.musicScoreEditor = this.$refs.musicScore.musicScoreEditor);
            this.editor.container = this.$refs.editorContainer;
            this.setEditorData(this.editorShared.currentData());
            shared.editorManager.getEditorVUEComponent = this;
            // if (this.$route && this.$route.query && this.$route.query.filePath) { // 根据路由参数打开文件
            //     this.setDefaultScore(this.$route.query.filePath);
            // }
            const filePath = this.$store.state.showFile;
            this.setDefaultScore(filePath)
        },
        beforeRouteEnter(to, from, next) {
            next()
        },
        methods: {
            isNeedMusicScore() {
                return this.editorType === EditorType.MusicScoreEditor ||
                    this.editorType === EditorType.MusicScorePlayer ||
                    this.editorType === EditorType.PerformanceTeaching ||
                    this.editorType === EditorType.WindInstruments ||
                    this.editorType === EditorType.MusicAppreciation;
            },
            isNeedMusicScoreSyncTimme() {
                // return this.editorType === EditorType.MusicScoreEditor;
                return true;
            },
            toolsChangeType(data) {
                if (data.editorType === this.$props.editorType) {
                    this.$refs.sketchpad.toolsChangeType(data);
                }
            },
            toolsAction(data) {
                if (data.editorType === this.$props.editorType) {
                    let type = data.type;
                    console.log(data.type)
                    if (type === EditorAction.Undo) {
                        let command = this.editor.undo();
                        command && command.targetType === CommandTargetType.Sketchpad && this.$refs.sketchpad.syncSketchpadData();
                    } else if (type === EditorAction.Redo) {
                        let command = this.editor.redo();
                        command && command.targetType === CommandTargetType.Sketchpad && this.$refs.sketchpad.syncSketchpadData();
                    } else if (type === EditorAction.Enlarge) {
                        this.scale = this.editor.scaleAction(0.2);
                    } else if (type === EditorAction.Narrow) {
                        this.scale = this.editor.scaleAction(-0.2);
                    } else if (type === EditorAction.ClearSketchpad) {
                        this.$refs.sketchpad.clearSketchpad();
                    } else if (type === SketchpadType.InsertFile) {
                        this.$refs.sketchpad.insertFile();
                    } else if (type === EditorAction.Switch) {
                        let musicScoreType = this.editorShared.currentData().musicScoreData.type;
                        this.editorShared.currentData().musicScoreData.jianXianSwitch();
                        this.$bus.emit(EventBusObsNames.JianXianSwitch, this.editorShared.currentData().musicScoreData.type);
                    }
                }
            },
            pageAction(data) {
                if (data.editorType === this.$props.editorType) {
                    let actionType = data.type;
                    let value = data.data;
                    if (actionType === LeftConfig.PageAction.Add) {
                        let pageIndex = this.editorShared.currentDataIndex + 1;
                        let editorData = value || new EditorData();
                        this.editorShared.addNewEditorData(pageIndex, editorData);
                        this.setEditorData(editorData);
                    } else if (actionType === LeftConfig.PageAction.Change) {
                        this.editorShared.currentDataIndex = value;
                        this.setEditorData(this.editorShared.currentData());
                    } else if (actionType === LeftConfig.PageAction.Delete) {
                        if (this.editorShared.jmcData.data.length === 1) {
                            this.$messageHelper.MessageInfo('至少保留一页！');
                        } else {
                            let _this = this;

                            function confirmDeleteAction() {
                                _this.editorShared.deleteCurrentData();
                                _this.setEditorData(_this.editorShared.currentData());
                            }

                            if (this.editorShared.currentData().history.stackLength) {
                                shared.deletePage.alert(confirmDeleteAction);

                            } else {
                                confirmDeleteAction();
                            }
                        }
                    }
                }
            },
            setEditorData(data) {
                this.$refs.sketchpad && this.$refs.sketchpad.setSketchpadData(null);
                this.$refs.musicScore && this.$refs.musicScore.setMusicScoreData(null);
                window.Indicator.open("正在加载…");
                setTimeout(() => {
                    let _this = this;
                    this.editor.data = data;
                    this.musicScoreDataNotnull = Object.isNotEmpty(data.musicScoreData);
                    this.$refs.sketchpad && this.$refs.sketchpad.setSketchpadData(data.sketchpadData);
                    this.$refs.musicScore && this.$refs.musicScore.setMusicScoreData(data.musicScoreData);
                    setTimeout(() => {
                        _this.editorContainer.animate({scrollTop: 0});
                    });
                    //缩略图截图赋值
                    this.$nextTick(() => {
                        window.Indicator.close();
                        // _this.editor.data.thumbnailBase64Data = shared.editorManager.getPNGBase64WithSVGString($("#editor_svg_container").html());
                        // l, t, r, b
                        setTimeout(() => {
                            let width = window.innerWidth;
                            let height = window.innerHeight;
                            _this.editor.data.thumbnailBase64Data = String.getBase64ImageStringFromArrayBuffer(shared.shareScreenBridge.captureScreen(width * 0.15, 20, width * 0.625, height * 0.66));
                        }, 500)
                    });
                    this.editorData = data;
                    this.$bus.emit(EventBusObsNames.OpenFileData, this.editorData);
                    this.$emit('onEditorDataChanged');
                });
            },
            onOpenFile(data, editorType, fileType) {
                if (fileType === FileType.MIDI) {
                    MidiParserData.parserData(data);
                } else {
                    if (editorType === this.editorType) {
                        this.setJMCData(JMCData.initWithJSONObject(data));
                        this.$bus.emit(EventBusObsNames.JianXianSwitch, shared.editorManager.currentMusicScoreData.type);
                    }
                }
            },
            setJMCData(jmcData) {
                this.editorShared.jmcData = jmcData;
                this.setEditorData(this.editorShared.currentData());
            },
            onInsertFile(data, editorType) {
                if (editorType === this.editorType) {
                    let jmcData = JMCData.initWithJSONObject(data);
                    let pageIndex = this.editorShared.currentDataIndex + 1;
                    this.editorShared.addNewJMCData(pageIndex, jmcData);
                    this.$bus.emit(EventBusObsNames.JianXianSwitch, shared.editorManager.currentMusicScoreData.type);
                    this.setEditorData(this.editorShared.currentData());
                }
            },
            insertOrReplaceEditorData(editorData) {
                let replaceIndex = null;
                for (let i = 0; i < this.editorShared.jmcData.data.length; i++) {
                    let tmpEditorData = this.editorShared.jmcData.data[i];
                    if (editorData.tmpId === tmpEditorData.tmpId) {
                        replaceIndex = i;
                        break;
                    }
                }
                if (replaceIndex === null) {
                    this.insertEditorData(editorData);
                    console.log('insertEditorData');
                } else {
                    this.editorShared.replaceEditorData(replaceIndex, editorData);
                    this.setEditorData(editorData);
                    console.log('replaceEditorData: ', replaceIndex);
                }
            },
            insertEditorData(editorData) {
                let pageIndex = this.editorShared.currentDataIndex + 1;
                this.editorShared.addNewEditorData(pageIndex, editorData);
                this.setEditorData(editorData);
            },
            setDefaultScore(filePath, openDefaultJMC) {
                let _this = this;
                //默认打开模板
                try {
                    if (!filePath) {
                        filePath = `${FileHelper.getDir(Folder.DefaultScore)}\\null.jmc`;
                        openDefaultJMC = true
                    }
                    let fileExtention = filePath.match(/\.([^\?\./]*)(\?|$)/)[1].toLowerCase();
                    let fileName = hex_sha1(filePath);
                    let fileFullName = fileName + "." + fileExtention;
                    if (openDefaultJMC) {
                        OpenJMCFile.openJMCFile(filePath, (data) => {
                            _this.onOpenFile(data, shared.editorManager.editorType, FileType.JMC)
                        });
                    }else{
                        Download.downloadFile(filePath, Folder.Temp,fileFullName, function (args) {
                            OpenJMCFile.openJMCFile(args.savePath, (data) => {
                                _this.$bus.$emit(EventBusObsTestName.SetModifuPathHistory, filePath);
                                _this.onOpenFile(data, shared.editorManager.editorType, FileType.JMC)
                            });
                        });
                    }
                } catch (e) {
                    console.log(e);
                }
            },
            editorContainerScroll(event) {
                this.editorType === EditorType.MusicReourcesCenter && $(this.$refs.editorContainer).scrollLeft(0);
                this.$emit('editorContainerScroll', event.target.scrollTop);
            },
            prohibitScroll(scrollTop) {  //禁止赏析页面的 白板滚动事件
                $(this.$refs.editorContainer).scrollTop(scrollTop);
            },
            mouse_down(event) {
                if (event.target && event.target.className !== 'img'
                    && event.target.className !== ''
                    && event.target.className !== 'sketchpadPlayerContainer'
                    && event.target.className !== 'sketchpadVideoPlayer'
                    && event.target.className !== 'sketchpadAudioPlayer') {
                    this.$refs.sketchpad && this.$refs.sketchpad.mouse_down(event);
                    this.$emit('editorMouseDown', event);
                    document.addEventListener('mousemove', this.mouse_move);
                    document.addEventListener('mouseup', this.mouse_up);
                    document.addEventListener('touchmove', this.mouse_move, {passive: false});
                    document.addEventListener('touchend', this.mouse_up);
                }
            },
            mouse_move(event) {
                // event.cancelBubble = true;
                // event.preventDefault();
                this.$refs.sketchpad && this.$refs.sketchpad.mouse_move(event);
                this.$emit('editorMouseMove', event);
            },
            mouse_up(event) {
                this.$refs.sketchpad && this.$refs.sketchpad.mouse_up(event);
                this.$emit('editorMouseUp', event);
                document.removeEventListener('mousemove', this.mouse_move);
                document.removeEventListener('mouseup', this.mouse_up);
                document.removeEventListener('touchmove', this.mouse_move);
                document.removeEventListener('touchend', this.mouse_up);
            },
            musicScoreTranslateX(value) {
                this.$refs.musicScore && this.$refs.musicScore.translateX(value);
            },
            setTransitionTimeInterval(duration) {
                this.$refs.musicScore && this.$refs.musicScore.setTransitionTimeInterval(duration);
            },
            insertImage(imagePath) {
                this.$refs.sketchpad && this.$refs.sketchpad.insertImageFun(imagePath);
            },
            setSyncTime(isSync) {
                this.$refs.musicScoreSyncTime && this.$refs.musicScoreSyncTime.showOrHideSyncMusicScoreContainer(isSync, this.editorData.musicScoreData);
            },
            setSketchpadScrollLeftNum(num) {
                this.$refs.sketchpad && this.$refs.sketchpad.setScrollLeft(num);
            },
            setScaleValue(value) {
                this.scale = value;
            },
            setTransformOrigin(obj) {
                // this.transformOriginString = `${obj.x}px ${obj.y}px`;
            },
            sketchpadTypeChangeFun(type) {
                this.$emit('sketchpadTypeChangeFun', type);
            }
        },
        watch: {
            $route: {
                handler: function (value) {
                    if (value && value.query && value.query.filePath) {
                        this.setDefaultScore(value.query.filePath);
                    }else{
                        this.setDefaultScore(`${FileHelper.getDir(Folder.DefaultScore)}\\null.jmc`, true);
                    }
                }
            }
        },
        beforeDestroy() {
            this.$bus.off(EventBusObsNames.DrawPageAction, this.pageAction);
            this.$bus.off(EventBusObsNames.DrawToolsAction, this.toolsAction);
            this.$bus.off(EventBusObsNames.DrawToolsChangeType, this.toolsChangeType);
            this.$bus.off(EventBusObsNames.DrawOpenFile, this.onOpenFile);
            this.$bus.off(EventBusObsNames.DrawInsertFile, this.onInsertFile);
        }
    }
</script>

<style scoped>
    #editorContainer {
        width: 100%;
        height: 100%;
        transform-origin: 0;
        touch-action: none;
    }

    #editor_svg_container {
        position: relative;
        width: 40000px;
        height: 2000px;
    }
</style>
